﻿using QuanLyGiaoVuService.CommandServices;
using QuanLyGiaoVuService.CommonServices;
using QuanLyGiaoVuService.ReportServices;
using QuanLyGiaoVuService.Utilities;
using QuanLyGiaoVuUI.Extensions.ExtendedAttributes;
using QuanLyGiaoVuUI.Extensions.Utilities;
using QuanLyGiaoVuUI.Models;
using QuanLyGiaoVuUI.Models.CaiDat;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace QuanLyGiaoVuUI.Controllers
{
    [GiangVienAuthorize(ChiGiaoVu = true)]
    public class CaiDatController : Controller
    {
        private IHocKyReportService _hocKyReportService;
        private IHocKyCommandService _hocKyCommandService;
        private IThamSoService _thamSoService;
        private ITemplateService _templateService;
        private ITaiLieuReportService _taiLieuReportService;

        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public CaiDatController(IHocKyReportService hockyReportService, IThamSoService thamSoService, ITemplateService templateService, IHocKyCommandService hocKyCommandService, ITaiLieuReportService taiLieuReportService)
        {
            _hocKyReportService = hockyReportService;
            _thamSoService = thamSoService;
            _templateService = templateService;
            _hocKyCommandService = hocKyCommandService;
            _taiLieuReportService = taiLieuReportService;
        }

        [HttpGet]
        public ActionResult Index()
        {
            CaiDatViewModel viewModel = new CaiDatViewModel();
            viewModel.HocKyHienTai = _thamSoService.GetGuid(ThamSoConstantUtility.HOCKYHIENTAI);
            viewModel.HocKyTiepTheo = _thamSoService.GetGuid(ThamSoConstantUtility.HOCKYTIEPTHEO);
            viewModel.ChoPhepDangKyDeTai = _thamSoService.GetBool(ThamSoConstantUtility.CHOPHEPDKDETAI);
            viewModel.ChoPhepDangKyLichThi = _thamSoService.GetBool(ThamSoConstantUtility.CHOPHEPDKLICHTHI);
            viewModel.ChoPhepXacNhanLop = _thamSoService.GetBool(ThamSoConstantUtility.CHOPHEPXACNHANLOP);
            viewModel.BatDauLichThi = _thamSoService.GetDateTime(ThamSoConstantUtility.BATDAULICHTHI);
            viewModel.KetThucLichThi = _thamSoService.GetDateTime(ThamSoConstantUtility.KETTHUCLICHTHI);
            viewModel.SoTinChiToiThieu = _thamSoService.GetInt(ThamSoConstantUtility.SOTINCHITOITHIEU);
            viewModel.ChoPhepSVDangKyDeTai = _thamSoService.GetBool(ThamSoConstantUtility.CHOPHEPSINHVIENDANGKYDETAI);

            viewModel.DanhSachHocKy = _hocKyReportService.GetAllHocKy().OrderBy(hk => hk.TenHocKy).OrderBy(hk => hk.NamHoc.Nam1);

            return View(viewModel);
        }

        [HttpPost]
        public JsonResult LuuCaiDat(CaiDatViewModel viewModel)
        {
            try
            {
                _thamSoService.SetThamSo(ThamSoConstantUtility.MAGIAOVU, UserUtility.GetCurrentUser().MaNguoiDung.ToString());
                if (viewModel.HocKyHienTai != Guid.Empty && viewModel.HocKyTiepTheo != Guid.Empty)
                {
                    Guid hkHienTaiId = (Guid)viewModel.HocKyHienTai;
                    Guid hkKeTiepId = (Guid)viewModel.HocKyTiepTheo;

                    if (hkHienTaiId == hkKeTiepId)
                        throw new ArgumentException("Học kỳ hiện tại và học kỳ kế tiếp phải khác nhau.");
                    var hocKyHienTai = _hocKyReportService.GetHocKyById(hkHienTaiId);
                    var hocKyKeTiep = _hocKyReportService.GetHocKyById(hkKeTiepId);
                    if (hocKyHienTai < hocKyKeTiep)
                    {
                        _thamSoService.SetThamSo(ThamSoConstantUtility.HOCKYHIENTAI, hkHienTaiId.ToString());
                        _thamSoService.SetThamSo(ThamSoConstantUtility.HOCKYTIEPTHEO, hkKeTiepId.ToString());
                    }
                    else
                    {
                        throw new ArgumentException("Học kỳ hiện tại phải trước học kỳ kế tiếp");
                    }
                }
                _thamSoService.SetThamSo(ThamSoConstantUtility.CHOPHEPDKDETAI, viewModel.ChoPhepDangKyDeTai.ToString());
                _thamSoService.SetThamSo(ThamSoConstantUtility.CHOPHEPDKLICHTHI, viewModel.ChoPhepDangKyLichThi.ToString());
                _thamSoService.SetThamSo(ThamSoConstantUtility.CHOPHEPXACNHANLOP, viewModel.ChoPhepXacNhanLop.ToString());
                _thamSoService.SetThamSo(ThamSoConstantUtility.CHOPHEPSINHVIENDANGKYDETAI, viewModel.ChoPhepSVDangKyDeTai.ToString());
                _thamSoService.SetThamSo(ThamSoConstantUtility.SOTINCHITOITHIEU, viewModel.SoTinChiToiThieu.ToString());
                if (viewModel.BatDauLichThi != null && viewModel.KetThucLichThi != null)
                {
                    if (viewModel.BatDauLichThi <= viewModel.KetThucLichThi)
                    {
                        _thamSoService.SetThamSo(ThamSoConstantUtility.BATDAULICHTHI, viewModel.BatDauLichThi.ToShortDateString());
                        _thamSoService.SetThamSo(ThamSoConstantUtility.KETTHUCLICHTHI, viewModel.KetThucLichThi.ToShortDateString());
                    }
                    else
                        throw new ArgumentException("Thời điểm bắt đầu thi phải trước thời điểm kết thúc thi");
                }
                return Json(new
                {
                    success = true
                });
            }
            catch (ArgumentException exception)
            {
                return Json(new
                {
                    success = false,
                    message = exception.Message
                });
            }
            catch
            {
                return Json(new
                {
                    success = false,
                    message = "Cập nhật không thành công."
                });
            }
        }

        [HttpGet]
        public ActionResult QuanLyTemplate()
        {
            QuanLyTemplateViewModel viewModel = new QuanLyTemplateViewModel();
            viewModel.DanhSachTaiLieu = _taiLieuReportService.GetAllTaiLieu(UserUtility.GetCurrentUser().MaNguoiDung, true, _thamSoService.GetGuid(ThamSoConstantUtility.MALOAIFILEMAU), null, null);
            viewModel.MaTaiLieuDangKyHocPhan = _thamSoService.GetGuid(ThamSoConstantUtility.MATAILIEUDANHSACHLOP);
            viewModel.MaTaiLieuDanhSachLichThi = _thamSoService.GetGuid(ThamSoConstantUtility.MATAILIEUDANHSACHLICHTHI);
            viewModel.MaTaiLieuDanhSachSinhVien = _thamSoService.GetGuid(ThamSoConstantUtility.MATAILIEUDANHSACHSINHVIEN);
            return View(viewModel);
        }

        [HttpPost]
        public JsonResult QuanLyTemplate(QuanLyTemplateViewModel viewModel)
        {
            try
            {
                _thamSoService.SetThamSo(ThamSoConstantUtility.MATAILIEUDANHSACHLOP, viewModel.MaTaiLieuDangKyHocPhan.ToString());
                _thamSoService.SetThamSo(ThamSoConstantUtility.MATAILIEUDANHSACHSINHVIEN, viewModel.MaTaiLieuDanhSachSinhVien.ToString());
                _thamSoService.SetThamSo(ThamSoConstantUtility.MATAILIEUDANHSACHLICHTHI, viewModel.MaTaiLieuDanhSachLichThi.ToString());
            }
            catch (Exception exception)
            {
                log.Error(exception.Message, exception);
                return Json(new { 
                    success = false,
                    message = "Cập nhật không thành công."
                });
            }
            return Json(new { 
                success = true
            });
        }

        [HttpGet]
        public ActionResult ChiTietTemplate(string tenTemplate)
        {
            var tokenList = _templateService.GetAllTemplateXMLElements(tenTemplate);
            return View("TemplateDKHP", tokenList);
        }

        [HttpGet]
        public ActionResult HocKyNamHoc()
        {
            var viewModel = new HocKyNamHocViewModel();
            viewModel.danhSachHocKy = _hocKyReportService.GetAllHocKy().OrderBy(hk => hk.TenHocKy).OrderBy(hk => hk.NamHoc.Nam1);
            viewModel.danhSachNamHoc = _hocKyReportService.GetAllNamHoc().OrderBy(nh => nh.Nam1);
            return View(viewModel);
        }

        [HttpPost]
        public JsonResult ThemHocKy(HocKyViewModel viewModel)
        {
            try
            {
                _hocKyCommandService.InsertHocKy(viewModel.ToHocKyDTO());
                return Json(new
                {
                    success = true
                });
            }
            catch (ArgumentException exception)
            {
                return Json(new
                {
                    success = false,
                    message = exception.Message
                });
            }
            catch
            {
                return Json(new
                {
                    success = false,
                    message = "Thêm học kỳ thất bại."
                });
            }
        }

        [HttpPost]
        public ActionResult ThemNamHoc(NamHocViewModel viewModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _hocKyCommandService.InsertNamHoc(viewModel.ToNamHocDTO());
                    return Json(new
                    {
                        success = true
                    });
                }
                else
                    return Json(new { 
                        success = false,
                        message = "Chưa nhập đủ thông tin"
                    });
            }
            catch (ArgumentException exception)
            {
                return Json(new
                {
                    success = false,
                    message = exception.Message
                });
            }
            catch
            {
                return Json(new
                {
                    success = false,
                    message = "Thêm năm học thất bại."
                });
            }
        }

        [HttpPost]
        [GiangVienAuthorize(ChiGiaoVu=true,ReturnJson=true)]
        public JsonResult LuuThamSo(string tenThamSo, string giaTri)
        {
            try
            {
                _thamSoService.SetThamSo(tenThamSo, giaTri);
                return Json(new
                {
                    success = true
                });
            }
            catch (Exception exception)
            {
                log.Error(exception.Message, exception);
                return Json(new { 
                    success = false,
                    message = "Lưu không thành công."
                });
            }
        }
    }
}